
/**
 * 函数防抖
 * @param {Function} fn 需要防抖处理的函数
 * @param {Number} wait 等待时间 1000 = 1s
 */
export function debounce(fn, wait) {
  let timerId = null
  let flag = true
  return function () {
    clearTimeout(timerId)
    if (flag) {
      fn.apply(this, arguments)
      flag = false
    }
    timerId = setTimeout(() => {
      flag = true
    }, wait)
  }
}

/**
 * 函数节流
 * @param {Function} fn 需要节流处理的函数
 * @param {Number} delay 节流时间 1000 = 1s
 */
export function throttle(fn, delay = 500) {
  let preTime = 0
  return function() {
    let now = Date.now()
    if (now - preTime > delay) {
      fn.apply(this, arguments)
      preTime = now
    }
  }
}

/**
 * 对象合并
 * @param {Object} target 合并后的目标对象
 */
export function merge(target) {
  for (let i = 1, j = arguments.length; i < j; i++) {
    let source = arguments[i] || {}
    for (const prop in source) {
      if (source.hasOwnProperty(prop)) {
        let value = source[prop]
        if (value !== undefined) {
          target[prop] = value
        }
      }
    }
  }
  return target
}
/**
 * 根据菜单数据返回重定向首页
 * @param {Array} nav 后台传过来的菜单数据
 * @returns {String} 重定向首页的path路径
 */
export function redirectPath(nav) {
  if (Object.prototype.toString.call(nav) === '[object Array]') {
    const formatRouter = (routes, newRoutes = []) => {
      routes.map(item => {
        if (item.children && item.children.length > 0) {
          formatRouter(item.children, newRoutes)
        } else {
          newRoutes.push(item)
        }
      })
      return newRoutes
    }
    const routes = formatRouter(nav).filter(item => {
      return item.fileName && item.visible
    })
    return routes[0]
  }
}
